/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package sw

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/common/logging"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/core/cryptosuite/csp/wrapper"
	core "git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/core"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/thirdparty/ichain/common/config"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/thirdparty/ichain/security/csp"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/thirdparty/ichain/security/csp/factory"
	"github.com/pkg/errors"
)

var logger = logging.NewLogger("ichainsdk/core")

// GetSuiteByConfig 根据配置获取非国密加密工具
func GetSuiteByConfig(config core.CryptoSuiteConfig) (core.CryptoSuite, error) {
	if config.SecurityProvider() != "sw" {
		return nil, errors.Errorf("Unsupported BCCSP Provider: %s", config.SecurityProvider())
	}

	opts := getOptsByConfig(config)
	myCsp, err := getBCCSPFromOpts(opts)
	if err != nil {
		return nil, err
	}
	return wrapper.NewCryptoSuite(myCsp, false), nil
}

// GetSuiteWithDefaultEphemeral 默认的加密配置生成加密工具，不建议直接使用
func GetSuiteWithDefaultEphemeral() (core.CryptoSuite, error) {
	opts := getEphemeralOpts()

	myCsp, err := getBCCSPFromOpts(opts)
	if err != nil {
		return nil, err
	}
	return wrapper.NewCryptoSuite(myCsp, false), nil
}

func getBCCSPFromOpts(opts *config.CSP) (csp.CSP, error) {
	myCsp, err := factory.InitFactory(opts)
	if err != nil {
		return nil, errors.Wrapf(err, "Could not initialize BCCSP")
	}
	return myCsp, nil
}

func getOptsByConfig(c core.CryptoSuiteConfig) *config.CSP {
	opts := &config.CSP{
		Default: csp.SW,
		SW: &config.SoftwareProvider{
			Hash:         c.SecurityAlgorithm(),
			Security:     c.SecurityLevel(),
			FileKeyStore: &config.FileKeyStore{KeyStore: c.KeyStorePath()},
		},
	}
	logger.Debug("Initialized SW cryptosuite")

	return opts
}

func getEphemeralOpts() *config.CSP {
	opts := &config.CSP{
		Default: csp.SW,
		SW: &config.SoftwareProvider{
			Hash:         csp.SHA2,
			Security:     256,
			FileKeyStore: nil,
		},
	}
	logger.Debug("Initialized ephemeral SW cryptosuite with default opts")

	return opts
}
